<script setup>
import topNav from "../../components/topNav.vue";
import { introApi } from "@/services/index";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { nextTick, ref, watch, onMounted } from "vue";
import { appInfo, loginSwitch } from "@/services/user";
// import topNav from "../../components/topNav.vue";
import { operation } from "@/utils/num.js";
import {
  appShopSelector,
  appScTransferCreate,
  StorePurchaseCreate,
} from "@/services/transfer";
import { base_URL } from "@/utils/http";

const goodsList = ref([]);
const payNum = ref(0);
const payPrice = ref(0);
const oldPayPrice = ref(0);
const goodsListNo = ref([]);
const selectShopObj = ref({});
const topHeight = ref(uni.getStorageSync("topHight") || 0);
onLoad((e) => {
  getAppShopSelector();
  if (uni.getStorageSync("goodsSel")) {
    goodsList.value = JSON.parse(uni.getStorageSync("goodsSel"));
    goodsList.value.forEach((item) => {
      payNum.value = payNum.value + item.transferNum;
      payPrice.value = operation(
        payPrice.value,
        operation(item.transferNum, item.salePrice, 2, "multiply"),
        2,
        "add"
      );
    });
  }

  if (uni.getStorageSync("shopselect")) {
    selectShopObj.value = JSON.parse(uni.getStorageSync("shopselect"));
  }
});

const ShopList = ref([]);
const showInShop = ref(false);
const selectid = ref("");
// showInShop.value = false;
// 门店选择
const shopSelectShow = () => {
  showInShop.value = true;
};

const getAppShopSelector = async () => {
  let res = await appShopSelector({});
  ShopList.value = res.data.datas;
};
const selectItem = ref({});
const shopSelect = (e) => {
  console.log(e);
  selectItem.value = e;
  selectid.value = e.id;
};
const selectTo = () => {
  selectShopObj.value.targetShopId = selectItem.value.id;
  selectShopObj.value.targetShopName = selectItem.value.name;
  uni.setStorageSync("shopselect", JSON.stringify(selectShopObj.value));

  showInShop.value = false;
};

const saveFun = () => {
  console.log("保存");
  //   console.log(form.value);
  // console.log(fileList.value[0].content);
  //   formMode.value.submit();
};
const value = ref(0);
const show = ref(false);

// 定义方法
const valChange = (e) => {
  console.log(e);

  let num = 0;
  let price = 0;

  setTimeout(() => {
    goodsList.value.forEach((item) => {
      num = num + item.transferNum;
      price = operation(
        price,
        operation(item.transferNum, item.newsalePrice, 2, "multiply"),
        2,
        "add"
      );
    });

    payPrice.value = price;
    payNum.value = num;
    uni.setStorageSync("goodsSel", JSON.stringify(goodsList.value));

    if (payNum.value == 0) {
      popupshow.value = false;
    }
  }, 100);
};
const confirmModal = () => {
  goodsList.value.forEach((item) => {
    item.transferNum = 0;
  });
  payNum.value = 0;
  show.value = false;
  uni.showToast({
    title: "清空成功",
    icon: "success",
    mask: true,
  });
  setTimeout(() => {
    uni.redirectTo({ url: "/pages/self_store/goods_sel/index" });
  }, 1500);
};
const rightClick = () => {
  console.log("rightClick");
};

const leftClick = () => {
  console.log("leftClick");
};
// const goPay = () => {
//   uni.navigateTo({
//     url: "/pages/cashier/goods_confirm/index",
//   });
// };
//清空
const clearFun = () => {
  show.value = true;
};

//支付
const isPay = ref(false);

const goPay = async () => {
  showPz.value = true;
};

const cerateTo = async () => {
  if (isPay.value == true) {
    return;
  }

  isPay.value = true;
  uni.showLoading({
    title: "提交中",
    mask: true,
  });

  let data = [];
  let upPrice = 0;

  goodsList.value.forEach((element) => {
    // price: element.price,
    if (element.transferNum > 0) {
      data.push({
        productId: element.id,
        purchaseNum: element.transferNum,
        salePrice: element.newsalePrice,
      });
    }
  });

  if (data.length <= 0) {
    isPay.value = false;
    return uni.showToast({
      title: "请选择商品",
      icon: "none",
    });
  }

  if (fileListThree.value.length <= 0) {
    isPay.value = false;
    return uni.showToast({
      title: "请选择上传原始单据",
      icon: "none",
    });
  }
  let purchaseCertificate = [];
  fileListThree.value.forEach((element) => {
    purchaseCertificate.push(element.url);
  });

  uni.setStorageSync("goodsSel", JSON.stringify(goodsList.value));

  try {
    let res = await StorePurchaseCreate({
      purchaseCertificate: purchaseCertificate,
      description: description.value,
      products: data,
    });
    if (res.code == 200) {
      isPay.value = false;
      uni.hideLoading();
      uni.showToast({
        title: "提交成功",
        icon: "none",
        duration: 2000,
        mask: true,
      });
      setTimeout(() => {
        uni.redirectTo({
          url: "/pages/self_store/home/index",
        });
      }, 1500);

      // let resData = res.data.datas;
    } else {
      uni.showToast({
        title: res.msg,
        icon: "none",
        mask: true,
      });
      isPay.value = false;
      uni.hideLoading();
    }

    console.log(res);
  } catch (e) {
    uni.showToast({
      title: e.msg,
      icon: "none",
      mask: true,
    });
    uni.hideLoading();
    isPay.value = false;
  }
};

const keyWord = ref(null);
const priceValue = ref(0);
const selectType = ref(1);
const selectTypeIndex = ref(0);
const selectItemObj = ref({});
const inp = (e) => {};

const hide = () => {
  // if (num.value > 0) {
  // } else {
  //   jsnum.value = 0;
  // }
  // isPayShow.value = false;
  keyWord.value.close();
};
const confirm = async () => {
  if (priceValue.value <= 0) {
    uni.showToast({
      title: "请输入正确金额",
      icon: "none",
    });
    return;
  }

  if (selectType.value == 1) {
    if (
      goodsList.value[selectTypeIndex.value].salePrice <
      Number(priceValue.value)
    ) {
      uni.showToast({
        title: "商品调价不能大于售价",
        icon: "none",
      });
      keyWord.value.open();
      return;
    }

    goodsList.value[selectTypeIndex.value].salePrice = Number(priceValue.value);
  }
  if (selectType.value == 2) {
    goodsListNo.value[selectTypeIndex.value].salePrice = Number(
      priceValue.value
    );
  }
  let num = 0;
  let price = 0;

  goodsList.value.forEach((item) => {
    num = num + item.transferNum;
    price = operation(
      price,
      operation(item.transferNum, item.salePrice, 2, "multiply"),
      2,
      "add"
    );
  });

  payPrice.value = price;
  payNum.value = num;

  // getcomputeBrokerage(Number(num.value));
  // productDataNo.value[selectNo.value].salePrice = Number(priceValue.value);
  // productDataNo.value[selectNo.value].transferNum = 1;

  // payPrice.value = operation(
  //   payPrice.value,
  //   Number(priceValue.value),
  //   2,
  //   "add"
  // );
};
const closePay = () => {
  // isPayShow.value = false;
  keyWord.value.close();
};
const priceClick = (item, index, type) => {
  selectItemObj.value = item;
  selectTypeIndex.value = index;
  selectType.value = type;

  console.log("item", selectTypeIndex.value, selectType.value);
  if (type == 1) {
    priceValue.value = String(item.salePrice);
    item.oldprice = item.price;
  }
  if (type == 2) {
    priceValue.value = String(item.salePrice);
  }
  keyWord.value.open();
};

//凭据弹框模块
const showPz = ref(false);
const fileListThree = ref([]);
const description = ref("");
// 删除图片
const deletePicThree = (event) => {
  fileListThree.value.splice(event.index, 1);
};

// 新增图片
const afterReadThree = async (event) => {
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  let lists = [].concat(event.file);
  let fileListLen = fileListThree.value.length;
  lists.map((item) => {
    fileListThree.value.push({
      ...item,
      status: "uploading",
      message: "上传中",
    });
  });
  for (let i = 0; i < lists.length; i++) {
    try {
      const result = await uploadFilePromise(lists[i].url);
      console.log(result);
      let item = fileListThree.value[fileListLen];
      fileListThree.value.splice(fileListLen, 1, {
        ...item,
        status: "success",
        message: "",
        url: result.data.url,
      });
      fileListLen++;
    } catch (e) {
      console.log(e);
      fileListThree.value.splice(i, 1);
      uni.showToast({
        title: e.message,
        icon: "none",
      });
    }
  }
};

const uploadFilePromise = (url) => {
  return new Promise((resolve, reject) => {
    let a = uni.uploadFile({
      url: base_URL + "/app/product/image", // 仅为示例，非真实的接口地址
      filePath: url,
      header: {
        "X-Auth-Token": uni.getStorageSync("X-Auth-Token"),
      },
      name: "file",
      formData: {
        user: "test",
      },
      success: (res) => {
        console.log(res);
        let data = JSON.parse(res.data);
        if (data.code == 200) {
          setTimeout(() => {
            resolve(data);
          }, 1000);
        } else {
          reject(data);
        }
      },
    });
  });
};
const ishowcamera = ref(false);
const getQX = () => {
  // #ifdef APP-PLUS

  const systemInfo = uni.getSystemInfoSync();

  if (systemInfo.osName === "android") {
    if (uni.getStorageSync("isspermission")) {
      return;
    } else {
      ishowcamera.value = true;
    }

    plus.android.requestPermissions(["android.permission.CAMERA"], (e) => {
      if (e.deniedAlways.length > 0) {
        // 弹出提示框解释为何需要权限，引导用户打开设置页面开启

        ishowcamera.value = false;
      } else if (e.deniedPresent.length > 0) {
        //权限被临时拒绝
        // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

        ishowcamera.value = false;
      } else if (e.deniedAlways.length > 0) {
        //权限被永久拒绝
        // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

        ishowcamera.value = false;
      } else {
        console.log("22222222222");
        plus.android.requestPermissions(
          ["android.permission.READ_EXTERNAL_STORAGE"],
          (e) => {
            if (e.deniedAlways.length > 0) {
              // 弹出提示框解释为何需要权限，引导用户打开设置页面开启

              ishowcamera.value = false;
            } else if (e.deniedPresent.length > 0) {
              //权限被临时拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

              ishowcamera.value = false;
            } else if (e.deniedAlways.length > 0) {
              //权限被永久拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

              ishowcamera.value = false;
            } else {
              ishowcamera.value = false;
              uni.setStorageSync("isspermission", true);
            }
          }
        );
      }
    });
  }
  return;
  // #endif
};
</script>

<template>
  <view class="bg">
    <topNav
      :title="'自采入库提交'"
      @save="saveFun"
      :border="true"
      rType="save"
    ></topNav>
    <!-- <up-navbar
      title="手机收银"
      bgColor="#ffffff"
      @rightClick="rightClick"
      :autoBack="true"
      :safeAreaInsetTop="true"
      :fixed="true"
      :placeholder="true"
      :leftText="'返回'"
      :border="true"
    >
      <template #right><text @click="clearFun">清空</text> </template>
    </up-navbar> -->
    <view class="content">
      <view
        class="content-top"
        :style="'top: calc( 88rpx + ' + topHeight + 'px);'"
      >
        <!-- <view class="content-top-shop">
          <text>调货至</text>
          <view class="content-top-shop-right">
            <text>{{ selectShopObj.targetShopName }}</text>
           
          </view>
        </view> -->
        <view class="content-top-up">
          <text>调货商品</text>
          <view class="content-top-shop-right" @click="clearFun"
            ><up-icon name="trash" color="#86909C" size="40rpx"></up-icon
            ><text>清空</text>
          </view>
        </view>
      </view>
      <view
        class="content-item"
        v-for="(item, index) in goodsList"
        :key="index"
      >
        <view class="content-item-left"
          ><image
            :src="
              item.image ||
              'https://cloud-erp.yibaitao.cn/0d2f4178-7754-4686-9213-b174f745258b.png'
            "
            mode="scaleToFill"
        /></view>
        <view class="content-item-right">
          <view class="content-item-right-title">
            <text>{{ item.name }}</text>
          </view>
          <view class="content-item-right-index">
            <view>
              <view class="content-item-right-num">
                <view class="content-item-right-num-left"
                  ><text>{{ item.categoryName }}</text>
                </view>
              </view>
              <!-- @click="priceClick(item, index, 1)" -->
              <view class="content-item-right-price"
                ><text>¥</text> {{ item.salePrice }}</view
              ></view
            >
            <view
              class="content-item-right-num-right"
              style="margin-top: 10rpx"
            >
              <text>价格¥{{ item.newsalePrice }} </text><br />
              <text>数量{{ item.transferNum }} </text>
              <!-- <up-number-box
                v-model="item.transferNum"
                @change="valChange"
                min="0"
              ></up-number-box> -->
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>

  <view class="bt_form">
    <view class="bt_form_k">
      <view class="bt_form_k_left">
        <view class="price"
          ><text>¥</text>{{ payPrice }}
          <view class="price-num">已选{{ payNum }}件</view></view
        >
      </view>
      <view class="bt_pay" @click="goPay">确定</view>
    </view>
  </view>

  <up-modal
    :show="show"
    title="温馨提示"
    :showCancelButton="true"
    confirmText="确认"
    cancelText="取消"
    @cancel="show = false"
    @confirm="confirmModal"
  >
    <view class="slot-content">
      <rich-text :nodes="'确定清空选择商品？'"></rich-text>
    </view>
  </up-modal>

  <up-popup
    v-model:show="showInShop"
    round="10"
    @close="showInShop = false"
    :safeAreaInsetBottom="true"
    :closeable="true"
  >
    <view class="popup-content">
      <view class="popup-content-title">
        <text>{{ "门店" }}</text>
      </view>
      <view class="popup-content-list">
        <scroll-view
          scroll-y="true"
          class="scroll-Y"
          @scrolltoupper="upper"
          @scrolltolower="lower"
          @scroll="scroll"
        >
          <view
            class="scroll-to"
            v-for="(item, index) in ShopList"
            :key="index"
            @click="shopSelect(item, 1)"
          >
            <view
              class="scroll-to-title"
              :class="item.id == selectid ? 'scroll-to-title-sel' : ''"
            >
              <text>{{ item.name }}</text>
            </view>
            <up-icon
              v-if="item.id == selectid"
              name="checkbox-mark"
              color="#1679FB"
              size="40rpx"
            ></up-icon>
          </view>
        </scroll-view>
      </view>
      <view class="popup-content-btn">
        <up-button
          class="bt-qx"
          type="default"
          :plain="true"
          text="取消"
          @click="showInShop = false"
        ></up-button>
        <up-button type="primary" @click="selectTo()" text="确定"></up-button>
      </view>
    </view>
  </up-popup>

  <up-popup
    v-model:show="showPz"
    round="10"
    @close="showPz = false"
    :safeAreaInsetBottom="true"
    :closeable="true"
  >
    <view class="popup-content">
      <view class="popup-content-title">
        <text>{{ "单据/备注" }}</text>
      </view>
      <view class="popup-content-list">
        <view class="popup-content-list2">
          <up-form
            labelPosition="left"
            labelWidth="180rpx"
            :model="form"
            :rules="rules"
            ref="form1"
          >
            <up-form-item
              label="原始单据"
              prop="fileListThree"
              borderBottom
              :required="true"
              ref="item1"
            >
              <up-upload
                @click="getQX"
                :fileList="fileListThree"
                @afterRead="afterReadThree"
                :sizeType="['compressed']"
                @delete="deletePicThree"
                name="1"
                multiple
                ref="uUpload"
                accept="image"
                :previewFullImage="true"
                :maxCount="5"
              ></up-upload>
            </up-form-item>
            <up-form-item
              label="备注"
              prop="description"
              :borderBottom="true"
              ref="item1"
            >
              <up-textarea
                v-model="description"
                placeholder="请输入内容"
                count
              ></up-textarea>
            </up-form-item>
          </up-form>
        </view>
      </view>

      <view class="popup-content-btn">
        <up-button
          class="bt-qx"
          type="default"
          :plain="true"
          text="取消"
          @click="showPz = false"
        ></up-button>
        <up-button type="primary" @click="cerateTo()" text="确定"></up-button>
      </view>
    </view>
  </up-popup>

  <view class="show-camera" v-if="ishowcamera">
    <view class="show-camera-k">
      <view class="show-sm"> 设备权限使用说明 </view>
      <view class="show-des">
        为了给您带来更好的服务，需要获取您的相机权限与读取图片及文件权限，用于更换上传图片、扫一扫等功能，对于您授权的信息我们竭尽全力提供安全保护。
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
@import "index.scss";
</style>
